package uutalk.netcloud.talk.base.util.thirdpart;

import com.qiniu.android.common.AutoZone;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.Configuration;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UploadManager;
import com.qiniu.android.utils.UrlSafeBase64;

import org.json.JSONObject;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import static android.text.TextUtils.isEmpty;

/**
 * Created by hujie on 17/4/6.
 */

public class QiNiuManager {

    private UploadManager uploadManager;
    private static QiNiuManager qiNiuManager;
    private static final String QINIU_ACCESSKEY = "ooWDuzGaOnqzt2CddFb5n1nQnPn6qUWwBKGaf_Cd";
    private static final String QINIU_SECRETKEY = "ufLDl1x9llZnRAjeFTisSLlKWBD55-g_BAk4WIX5";
    public static final String QINIU_HOST = "http://onyyki115.bkt.clouddn.com/";


    private QiNiuManager() {
        Configuration configuration = new Configuration.Builder().zone(AutoZone.autoZone).build();
        uploadManager = new UploadManager(configuration);


    }


    /**
     * 上传图片
     * @param file
     * @param completionHandler
     */
    public void uploadImage(File file, UpCompletionHandler completionHandler) {
        uploadManager.put(file, createImageOssObjectKeyByFile(file.getName()), getToken(), completionHandler, null);
    }


    /**
     * 上传语音
     */
    public void uploadPCM(File file, String key, UpCompletionHandler completionHandler) {
        uploadManager.put(file, key, getToken(), completionHandler, null);
    }

    /**
     * 同步上传语音
     */
    public String syncUploadPCM(File file, String key, UpCompletionHandler completionHandler) {
        ResponseInfo responseInfo = uploadManager.syncPut(file, key, getToken(), null);
        if (responseInfo.isOK()) {
            return key;
        }
        return null;
    }


    public static QiNiuManager getInstance() {
        if (qiNiuManager == null) {
            qiNiuManager = new QiNiuManager();
        }
        return qiNiuManager;
    }

    private String getToken() {
        try {
            // 1 构造上传策略
            JSONObject _json = new JSONObject();
            long _dataline = System.currentTimeMillis() / 1000 + 3600;
            _json.put("deadline", _dataline);// 有效时间为一个小时
            _json.put("scope", "uutalk");
            String _encodedPutPolicy = UrlSafeBase64.encodeToString(_json
                    .toString().getBytes());
            byte[] _sign = HmacSHA1Encrypt(_encodedPutPolicy, QINIU_SECRETKEY);
            String _encodedSign = UrlSafeBase64.encodeToString(_sign);
            String _uploadToken = QINIU_ACCESSKEY + ':' + _encodedSign + ':'
                    + _encodedPutPolicy;
            return _uploadToken;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "";
    }


    /**
     *
     使用 HMAC-SHA1 签名方法对encryptText进行签名
     *
     * @param encryptText
     *            被签名的字符串
     * @param encryptKey
     *            密钥
     * @return
     * @throws Exception
     */
    private static byte[] HmacSHA1Encrypt(String encryptText, String encryptKey)
            throws Exception {
        byte[] data = encryptKey.getBytes("UTF-8");
        // 根据给定的字节数组构造一个密钥,第二参数指定一个密钥算法的名称
        SecretKey secretKey = new SecretKeySpec(data, "HmacSHA1");
        // 生成一个指定 Mac 算法 的 Mac 对象
        Mac mac = Mac.getInstance("HmacSHA1");
        // 用给定密钥初始化 Mac 对象
        mac.init(secretKey);
        byte[] text = encryptText.getBytes("UTF-8");
        // 完成 Mac 操作
        return mac.doFinal(text);
    }

    public UploadManager getUploadManager() {
        return uploadManager;
    }

    private static String createImageOssObjectKey(String keyName) {
        String dateFormat = new SimpleDateFormat("yyyy/MM/dd/HH").format(new Date());
        StringBuilder sb = new StringBuilder("pic/");
        sb.append(dateFormat)
                .append("/")
                .append(keyName);

        return sb.toString();
    }




    public static String createImageOssObjectKeyByFile(String fileName) {

        String type = ".jpg";
        if (!isEmpty(fileName)) {
            int point = fileName.lastIndexOf('.');
            type = fileName.substring(point + 1);
        }
        return createImageOssObjectKey(createOssObjectKeyNameByType(type));
    }


    /**
     * 创建图片的ossobject keyname
     * @return
     */
    private static String createOssObjectKeyNameByType(String type) {
        long currentTimeMillis = System.currentTimeMillis();
        UUID uuid = UUID.randomUUID();
        String uniqueId = uuid.toString();
        return new StringBuffer().append(currentTimeMillis).append("-").append(uniqueId).append(".").append(type).toString();
    }

}
